<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商家中心</el-breadcrumb-item>
      <el-breadcrumb-item>菜品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="5">
          <el-button type="primary" @click="addDialogVisible = true">添加菜品</el-button>
        </el-col>
      </el-row>
      <el-table :data="foodList" stripe border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table :data="scope.row.remarks">
              <el-table-column type="index" label="序号"></el-table-column>
              <el-table-column label="评分" prop="comment">
                <template slot-scope="remark">
                  <el-rate v-model="remark.row.comment" disabled text-color="#ff9900"></el-rate>
                </template>
              </el-table-column>
              <el-table-column label="评价" prop="detail"></el-table-column>
              <el-table-column label="评价用户" prop="user.uname"></el-table-column>
              <el-table-column label="评价时间" prop="time"></el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="预览图">
          <template slot-scope="scope">
            <el-image style="width: 150px; height: 100px" :src="imageBaseUrl + scope.row.icon + '.jpg'" fit="scale-down">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="fname" label="菜品名"></el-table-column>
        <el-table-column prop="detail" label="菜品描述"></el-table-column>
        <el-table-column prop="comment" label="评分">
          <template slot-scope="scope">
            <el-rate v-model="scope.row.comment" disabled text-color="#ff9900"></el-rate>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.fid)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeFoodById(scope.row.fid)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" background>
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加菜品"
      :visible.sync="addDialogVisible"
      width="50%"
      append-to-body
      @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="菜品名" prop="fname">
          <el-input v-model="addForm.fname"></el-input>
        </el-form-item>
        <el-form-item label="麻辣" prop="mspicy">
          <el-rate v-model="addForm.mspicy" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="辣度" prop="spicy">
          <el-rate v-model="addForm.spicy" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="鲜度" prop="fresh">
          <el-rate v-model="addForm.fresh" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="苦度" prop="bitter">
          <el-rate v-model="addForm.bitter" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="咸度" prop="salt">
          <el-rate v-model="addForm.salt" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="酸度" prop="sour">
          <el-rate v-model="addForm.sour" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="甜度" prop="sweet">
          <el-rate v-model="addForm.sweet" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="菜品描述" prop="detail">
          <el-input type="textarea" v-model="addForm.detail"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFood">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改菜品信息"
      :visible.sync="editDialogVisible"
      width="50%"
      append-to-body
      @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="菜品名" prop="fname">
          <el-input v-model="editForm.fname"></el-input>
        </el-form-item>
        <el-form-item label="麻辣" prop="mspicy">
          <el-rate v-model="editForm.mspicy" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="辣度" prop="spicy">
          <el-rate v-model="editForm.spicy" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="鲜度" prop="fresh">
          <el-rate v-model="editForm.fresh" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="苦度" prop="bitter">
          <el-rate v-model="editForm.bitter" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="咸度" prop="salt">
          <el-rate v-model="editForm.salt" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="酸度" prop="sour">
          <el-rate v-model="editForm.sour" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="甜度" prop="sweet">
          <el-rate v-model="editForm.sweet" class="my-rate" allow-half></el-rate>
        </el-form-item>
        <el-form-item label="菜品描述" prop="detail">
          <el-input type="textarea" v-model="editForm.detail"></el-input>
        </el-form-item>
      </el-form>
      <div>
        <span>上传菜品图片</span>
        <el-upload
          class="upload-demo"
          drag
          :action="uploadAction"
          multiple
          :on-success="uploadSuccess"
          :before-upload="beforeUpload"
          :data="editForm">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将菜品图片拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg文件，且不超过2MB</div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFood">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Food',
  data () {
    const checkSpace = (rule, value, callback) => {
      const regSpace = /\s/
      if (!regSpace.test(value)) {
        return callback()
      }
      callback(new Error('不能有空格'))
    }
    return {
      foodList: [],
      queryInfo: {
        rid: window.sessionStorage.getItem('rid'),
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      imageBaseUrl: this.$axios.defaults.baseURL + 'static/image/',
      uploadAction: this.$axios.defaults.baseURL + 'restaurant/food/upload',
      editDialogVisible: false,
      addDialogVisible: false,
      editForm: {},
      editFormRules: {
        fname: [
          {
            required: true,
            message: '请填写菜品名',
            trigger: 'blur'
          },
          {
            validator: checkSpace,
            trigger: 'blur'
          }
        ]
      },
      addForm: {
        rid: window.sessionStorage.getItem('rid'),
        fname: '',
        mspicy: 0,
        spicy: 0,
        fresh: 0,
        bitter: 0,
        salt: 0,
        sour: 0,
        sweet: 0,
        detail: ''
      },
      addFormRules: {
        fname: [
          {
            required: true,
            message: '请填写菜品名',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 8,
            message: '菜品名的长度在1到8个字符之间',
            trigger: 'blur'
          },
          {
            validator: checkSpace,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getFoodList()
  },
  methods: {
    async showEditDialog (fid) {
      const id = { fid: fid }
      const { data: res } = await this.$axios.get('/restaurant/food/queryByID', { params: id })
      if (res.status !== 2000) {
        return this.$message.error('获取菜品信息失败')
      }
      this.editForm = res.data.food
      this.editDialogVisible = true
    },
    async removeFoodById (fid) {
      const confirmResult = await this.$confirm('此操作将永久删除该菜品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击确定删除时，返回字符串 confirm
      // 点击取消删除时，返回字符串 cancel
      if (confirmResult === 'cancel') {
        return this.$message.info('已取消删除')
      }
      const id = { fid: fid }
      const { data: res } = await this.$axios.delete('/restaurant/food/delete', { params: id })
      if (res.status !== 2000) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      await this.getFoodList()
    },
    async getFoodList () {
      const { data: res } = await this.$axios.get('/restaurant/getFoods', { params: this.queryInfo })
      if (res.status !== 2000) {
        return this.$message.error('获取菜品失败')
      }
      this.foodList = res.data.foods
      this.total = res.data.total
    },
    // 监听每页显示多少条信息
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getFoodList()
    },
    // 监听当前所在页码数
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getFoodList()
    },
    editFood () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$axios.post('/restaurant/food/update', this.editForm)
        if (res.status !== 2000) {
          return this.$message.error('修改信息失败')
        }
        this.editDialogVisible = false
        this.$message.success('修改菜品信息成功')
        await this.getFoodList()
      })
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    uploadSuccess () {
      this.getFoodList()
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB')
      }
      return isJPG && isLt2M
    },
    addFood () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$axios.post('/restaurant/food/add', this.addForm)
        if (res.status !== 2000) {
          return this.$message.error('添加菜品失败')
        }
        this.$message.success('添加菜品成功')
        this.addDialogVisible = false
        await this.getFoodList()
      })
    }
  }
}
</script>

<style scoped>
.my-rate {
  margin-top: 10px;
}
</style>
